import wheels.pi.aio as aio

from wheels.pi.aio.AsyncOperation import ConnectOperation
from wheels.pi.aio.Proactor import EventHandler


class AsyncConnector(object):

    class _ProactiveHandler(EventHandler):

        def __init__(self, handler, act):
            self._handler = handler
            self._act = act

        def handle_connect(self):
            self._handler.handle_event("connect", self._act)


    def __init__(self, handle, proactor, handler):
        self._handle = handle
        self._proactor = proactor
        self._handler = handler


    def connect(self, remote_address, act = None):
        op = ConnectOperation(self._handle, remote_address)
        proactive = AsyncConnector._ProactiveHandler(self._handler, act)
        aio.register(op, self._proactor, proactive)
